package chaoyue.study.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Slf4j
@RestController
@RequestMapping("test")
public class TestFileUploadController {

    /**
     * 文件上传
     */
    @PostMapping("/upload")
    public String handleFileUpload(@RequestParam("file") MultipartFile file, @RequestParam String myParam) {
        try {
            if (file.isEmpty()) {
                return "Please select a file to upload";
            }
            log.info("getName() -> {}", file.getName());
            log.info("getOriginalFilename() -> {}", file.getOriginalFilename());
            log.info("getSize() -> {}", file.getSize());
            log.info("getContentType() -> {}", file.getContentType());
            byte[] bytes = file.getBytes();
            // 写入本地
            Path path = Paths.get("/Users/chaoyue/Downloads")
                    .resolve("文件上传_" + file.getOriginalFilename());
            Files.write(path, bytes);
            return "You successfully uploaded " + file.getOriginalFilename() + "!" + " myParam: " + myParam;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "File upload failed";
    }
}
